<template>
  <div class="head-container">
    <div class="icon-methods">
      <span class="title"> 数据源</span>
      <div class="flex-align-center">
        <el-tooltip effect="dark" content="新增文件夹" placement="top">
          <el-icon class="custom-icon btn" :style="{ marginRight: '20px' }" @click="handleDatasourceTree('folder')">
            <Icon :size="18" icon="ep:folder-add" />
          </el-icon>
        </el-tooltip>
        <el-tooltip effect="dark" content="修改数据源" placement="top">
          <el-icon class="custom-icon btn" @click="editDatasource()">
            <Icon :size="18"  icon="ep:files" />
          </el-icon>
        </el-tooltip>
      </div>
    </div>
    <el-input v-model="deptName" class="mb-20px" clearable placeholder="请输入数据库名称">
      <template #prefix>
        <Icon icon="ep:search" />
      </template>
    </el-input>
  </div>
  <div class="head-container">
    <el-tree 
    ref="treeRef" 
    :data="deptList" 
    :expand-on-click-node="false" 
    :filter-node-method="filterNode"
    :props="defaultProps" default-expand-all highlight-current node-key="id" @node-click="handleNodeClick" />
  </div>

  <el-dialog
    v-model="dialogVisible"
    title="创建文件夹"
    width="800"
  >
    <el-form label-position="top" :model="datasetForm" label-width="10px">
      <el-form-item label="数据源名称" prop="name">
        <el-input v-model="datasetForm.name" placeholder="请输入数据源名称" />
      </el-form-item>
      <!--mysql的配置信息：描述、IP地址、端口、数据库名称、用户名、密码、额外的JDBC连接字符串-->
      <el-form-item label="描述" prop="description">
        <el-input v-model="datasetForm.description" placeholder="请输入描述" />
      </el-form-item>
      <!-- IP地址 -->
      <el-form-item label="IP地址" prop="ip">
        <el-input v-model="datasetForm.ip" placeholder="请输入IP地址" />
      </el-form-item>
      <!-- 端口 -->
      <el-form-item label="端口" prop="port">
        <el-input v-model="datasetForm.port" placeholder="请输入端口" />
      </el-form-item>
      <!-- 数据库名称 -->
      <el-form-item label="数据库名称" prop="dbName">
        <el-input v-model="datasetForm.dbName" placeholder="请输入数据库名称" />
      </el-form-item>
      <!-- 用户名 -->
      <el-form-item label="用户名" prop="username">
        <el-input v-model="datasetForm.username" placeholder="请输入用户名" />
      </el-form-item>
      <!-- 密码 --> 
      <el-form-item label="密码" prop="password">
        <el-input v-model="datasetForm.password" type="password" placeholder="请输入密码" />
      </el-form-item>
      <!-- 额外的JDBC连接字符串 -->
      <el-form-item label="额外的JDBC连接字符串" prop="jdbcUrl">
        <el-input v-model="datasetForm.jdbcUrl" placeholder="请输入额外的JDBC连接字符串" />
      </el-form-item>
    </el-form> 

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="createFolder">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ElTree } from 'element-plus'
// const { t } = useI18n()

import { defaultProps, handleTree } from '@/utils/tree'
import * as DsApi from '@/api/data/dscategory'
import { onMounted, onBeforeMount } from 'vue'

defineOptions({ name: 'DsTree' })

const deptName = ref('')
const deptList = ref<Tree[]>([]) // 树形结构
const treeRef = ref<InstanceType<typeof ElTree>>()
const dialogVisible = ref(false)

const datasetForm = reactive({
  id: undefined, // 编号
  name: "", // 名称
  description: "", // 描述
  type: "", // 类型
  pid: undefined,// 父级ID
  ip: "", // IP地址
  port: "", // 端口
  dbName: "", // 数据库名称
  username: "", // 用户名
  password: "", // 密码
  configuration: {}, // 配置项
  jdbcUrl: "useUnicode=true&characterEncoding=utf8&serverTimezone=UTC&useSSL=false" // 额外的JDBC连接字符串
})

onBeforeMount(() => { 
  console.log('组件实例已创建');
  // 可以在这里进行API请求或其他初始化逻辑
})

const handleDatasourceTree = (type: string) => {
  // TODO
  console.log('handleDatasourceTree', type)
  dialogVisible.value = true
}




const editDatasource = () => {
  // TODO: Implement the logic for editing a datasource
  console.log('Editing datasource')
  dialogVisible.value = true;
  DsApi.DsCategoryApi.getDsCategory(datasetForm.id).then((res) => {
    datasetForm.name = res.name
    datasetForm.description = res.description
    datasetForm.ip = res.configuration.ip
    datasetForm.port = res.configuration.port
    datasetForm.dbName = res.configuration.dbName
    datasetForm.username = res.configuration.username
    datasetForm.password = res.configuration.password
    datasetForm.jdbcUrl = res.configuration.jdbcUrl
  })
  // 这里可以添加逻辑来处理数据源的编辑操作，例如打开一个编辑表单等
}

const createFolder = () => {
  // TODO: Implement the logic for creating a folder
  console.log('Creating folder:', datasetForm.name);
  //获取数据库连接
  let jdbcUrl = `jdbc:mysql://${datasetForm.ip}:${datasetForm.port}/${datasetForm.dbName}` + 
  `?user=${datasetForm.username}&password=${datasetForm.password}` +
  datasetForm.jdbcUrl ? `&${datasetForm.jdbcUrl}` : ''
  console.log('jdbcUrl', jdbcUrl);
  DsApi.DsCategoryApi.createDsCategory({
      id: datasetForm.id ?? null,
      name: datasetForm.name,
      description: datasetForm.description,
      type: 'mysql',
      pid: undefined,
      configuration : jdbcUrl,
      // configuration: JSON.stringify({
      //   ip: datasetForm.ip,
      //   port: datasetForm.port,
      //   dbName: datasetForm.dbName,
      //   username: datasetForm.username,
      //   password: datasetForm.password,
      //   jdbcUrl: datasetForm.jdbcUrl
      // }),// Add required properties from DsCategoryVO
      status: "1"
    }
  ).then(() => {
    dialogVisible.value = false
    formReset()
    getTree()
    
  })
}

const formReset = () => {
  datasetForm.id = undefined
  datasetForm.name = ''
  datasetForm.description = ''
  datasetForm.type = ''
  datasetForm.configuration = {
    ip: '',
    port: '',
    dbName: '',
    username: '',
    password: '',
    jdbcUrl: ''
  }
}

/** 获得部门树 */
const getTree = async () => {
  const res = await DsApi.DsCategoryApi.getDsCategoryList();
  deptList.value = []
  deptList.value.push(...handleTree(res))
}

/** 基于名字过滤 */
const filterNode = (name: string, data: Tree) => {
  if (!name) return true
  return data.name.includes(name)
}

/** 处理部门被点击 */
const handleNodeClick = async (row: { [key: string]: any }) => {
  emits('node-click', row)
}
const emits = defineEmits(['node-click'])

/** 监听deptName */
watch(deptName, (val) => {
  treeRef.value!.filter(val)
})

/** 初始化 */
onMounted(async () => {
  await getTree()
})

// Not needed since we're using the Composition API lifecycle hooks
</script>
<style lang="scss" scoped>

.icon-methods {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    font-size: 20px;
    font-weight: 500;
    color: var(--TextPrimary, #1f2329);
    padding-bottom: 16px;
    .title {
      margin-right: auto;
      font-size: 16px;
      font-style: normal;
      font-weight: 500;
      line-height: 24px;
    }
    .custom-icon {
      font-size: 20px;
      &.btn {
        color: var(--ed-color-primary);
      }
      &:hover {
        cursor: pointer;
      }
    }
  }

.flex-align-center {
  display: flex;
  align-items: center;

  &.icon {
    .ed-icon {
      margin-right: 6px;
    }
  }
}

.custom-icon {
  &.btn {
    color: var(--ed-color-primary);
  }

  &:hover {
    cursor: pointer;
  }
}


</style>
